package com.xxx.lease.web.admin.schedule;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xxx.lease.common.minio.MinioProperties;
import com.xxx.lease.model.entity.LeaseAgreement;
import com.xxx.lease.model.enums.LeaseStatus;
import com.xxx.lease.web.admin.service.GraphInfoService;
import com.xxx.lease.web.admin.service.LeaseAgreementService;
import io.minio.MinioClient;
import io.minio.RemoveObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;

@Component
public class ScheduleTasks {

    @Autowired
    private LeaseAgreementService leaseAgreementService;
    @Autowired
    private MinioProperties minioProperties;
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private GraphInfoService graphInfoService;

    /*
    *   自动检查租约状态 （2 已签约，5 退租待确认）
    *   如果租约到期（lease_end_date 租约结束日期 小于 当前日期） 自动把状态设置为已到期 3
    *   lease_end_date 2024-1-2   2024-9-23 now
    *
    * */


    @Scheduled(cron = "0 0-30 5 * * *")
    public void checkLeaseStatus(){
        LambdaUpdateWrapper<LeaseAgreement> updateWrapper = new LambdaUpdateWrapper<>();
        Date now = new Date();
        updateWrapper.lt(LeaseAgreement::getLeaseEndDate, now);
        updateWrapper.in(LeaseAgreement::getStatus, LeaseStatus.SIGNED, LeaseStatus.WITHDRAWING);
        updateWrapper.set(LeaseAgreement::getStatus, LeaseStatus.EXPIRED);
        leaseAgreementService.update(updateWrapper);
    }


    @Scheduled(cron = "0 0-30 6 * * *")
    public void removeMinioImage(){
        try {
            List<String> urlList = graphInfoService.listRemoveImage();
            for (String url : urlList) {
                if(url != null){
                    String fileName = url.substring(url.lastIndexOf("/") + 1);
                    minioClient.removeObject(RemoveObjectArgs.builder().bucket(minioProperties.getBucketName()).object(fileName).build());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
